<template>
  <div class="data">
    <!-- 列表展示区 -->
    <div class="pointList">
      <!-- 左侧按钮 -->
      <i
        class="el-icon-arrow-left"
        :class="{ invalid: this.page == 1 }"
        @click="leftBtn"
      />

      <!-- 列表 -->
      <div class="pointLayout">
        <div
          v-for="attribute in deviceAttributes"
          :key="attribute.token"
          class="cardItem"
        >
          <el-card
            class="listCard"
            shadow="never"
            :class="{ bg_color: index_token == attribute.token }"
          >
            <div class="itemBox" @click="changeStyle(attribute.token)">
              <div
                class="parameter"
                :class="{ word_color: index_token == attribute.token }"
              >
                {{ attribute.name }}
              </div>
              <div
                class="number"
                :class="{ word_color: index_token == attribute.token }"
              >
                <span>{{ attribute.dataValue }}{{ attribute.unit }}</span>
              </div>
              <div style="height: 15%;width:100%">
                <div
                  v-if="
                    attribute.percentValue != '' &&
                      attribute.percentValue !== '0.00'
                  "
                  class="percentage"
                  :class="
                    (attribute.percentValue > 0
                      ? 'percentage_up'
                      : 'percentage_down') +
                      (index_token == attribute.token ? ' word_color' : '')
                  "
                >
                  <i
                    :class="
                      attribute.percentValue > 0
                        ? 'el-icon-top'
                        : 'el-icon-bottom'
                    "
                  />{{ replaceStr(attribute.percentValue) }}%
                </div>
                <div
                  v-else-if="
                    attribute.percentValue != '' &&
                      attribute.percentValue == '0.00'
                  "
                  class="percentage percentage_com"
                >
                  {{ replaceStr(attribute.percentValue) }}%
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <!-- 右侧按钮 -->
      <i
        class="el-icon-arrow-right"
        :class="{ invalid: this.total / this.pageSize <= this.page }"
        @click="rightBtn"
      />
    </div>
    <div class="smallPaging">
      <el-pagination
        v-if="total > 0"
        small
        layout="prev, pager, next"
        :current-page.sync="page"
        :page-size.sync="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 折线图区 -->
    <div class="data-charts">
      <div ref="chart" v-init-screen-h="30" class="chart" />
    </div>
  </div>
</template>

<script>
import { formatTime2 } from "@/views/common/js/utils.js";
import { formatDate } from "@/filter/index";
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import { getDeviceTypeAttributes } from "@/api/deviceType";
import {
  echartOptionInit,
  echartOptionLine
} from "@/views/common/js/device/echartsUtils.js";
import { getCookie } from "@/utils/auth";
export default {
  props: {
    deviceToken: {
      type: String
    },
    deviceTypeToken: {
      type: String
    }
  },
  data() {
    return {
      index_token: "",
      page: 1,
      pageSize: 7,
      total: 0,
      index_token: "",
      initmqtt: "",
      client: "",
      tenantTopic: "",
      lineChart: {},
      option: {},
      xData: [],
      yData: [],
      lend: "",
      deviceAttributes: [],
      attributeSelectTokens: []
    };
  },
  mounted() {
    // console.log(formatTime2(new Date()));
  },
  destroyed() {
    // 页面关闭,关闭mqtt连接
    if (this.client) {
      this.client.end();
    }
  },
  methods: {
    replaceStr(data) {
      return data.replace("-", "");
    },
    // 上一页
    leftBtn() {
      if (this.page > 1) {
        this.handleCurrentChange(this.page - 1);
      }
    },
    // 下一页
    rightBtn() {
      if (this.total / this.pageSize > this.page) {
        this.handleCurrentChange(this.page + 1);
      }
    },
    // 页面数据初始化
    init() {
      this.getDeviceRunTimeData();
      if (this.client == "") {
        this.receiveData();
        this.drawLine();
      }
    },
    // 执行参数过滤
    handleParamsFilter() {
      this.page = 1;
      this.clearLineData();
      this.getDeviceRunTimeData();
    },
    // 获取点位列表
    getDeviceRunTimeData() {
      var params = {
        page: this.page,
        pageSize: this.pageSize,
        attributeTokenList: this.attributeSelectTokens
      };
      getDeviceTypeAttributes(params, this.deviceTypeToken).then(res => {
        const r = res.data;
        // 必须先添加value属性,否则后面不会实时响应变化
        this.deviceAttributes = [];
        r.results.forEach(v => {
          v.dataValue = "";
          v.percentValue = "";
          if (v.name.indexOf("百分比") > 0) {
            v.unit = "%"; // 单位
          } else if (v.name.indexOf("温度") > 0) {
            v.unit = "℃";
          } else {
            v.unit = "";
          }
          this.deviceAttributes.push(v);
        });
        this.total = r.numResults;
        if (this.deviceAttributes.length > 0) {
          this.index_token = this.deviceAttributes[0].token;
        }
      });
    },
    // 分页调用
    handleCurrentChange(val) {
      this.page = val;
      this.index_token = "";
      this.clearLineData();
      this.getDeviceRunTimeData();
    },
    // 切换点位
    changeStyle(token) {
      if (this.index_token != token) {
        this.index_token = token;
        this.clearLineData();
      }
    },
    // mqtt接收数据
    receiveData() {
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + "/mqtt"
      };
      this.tenantToken = this.$store.state.user.tenant.token;
      //
      // this.tenantTopic = "SuperLink/" + this.tenantToken + "/input/json";
      this.tenantTopic = `$avic/superlink/iot/${this.tenantToken}/${this.deviceToken}/measurement`;
      this.initmqtt = new initMqtt(param);
      this.client = this.initmqtt.connect(() => {
        console.log("mqtt连接成功,开始订阅主题");
        this.client.subscribe(this.tenantTopic);
      });
      this.onMessageArrived();
    },
    // 接收数据
    onMessageArrived() {
      this.client.on("message", (topic, message) => {
        var obj = JSON.parse(message.toString());
        if (obj.type == "DeviceMeasurement") {
          if (obj.deviceToken == this.deviceToken) {
            var metadata = obj.request.metadata;
            // console.log("A=>:::", this.client);
            console.log("B=>:::", metadata);
            for (var index in metadata) {
              // echarts中数据添加
              if (this.index_token == index) {
                // console.log(obj.request.eventDate);
                this.xData.push(
                  formatDate(obj.request.eventDate, "HH:mm:ss", true)
                );
                this.yData.push(metadata[index]);
                this.drawLineData();
                // 暂时只保留1800条数据
                if (this.yData.length > 1800) {
                  this.xData.splice(0, 1);
                  this.yData.splice(0, 1);
                }
              }
              // 点位列表中实时数据
              this.deviceAttributes.forEach(v => {
                if (v.token == index) {
                  if (
                    metadata[index] &&
                    v.dataValue &&
                    v.dataValue != 0 &&
                    metadata[index] !== "true" &&
                    metadata[index] !== "false"
                  ) {
                    v.percentValue =
                      v.dataValue &&
                      (
                        ((metadata[index] - v.dataValue) / v.dataValue) *
                        100
                      ).toFixed(2);
                    v.dataValue = metadata[index];
                  } else {
                    if (metadata[index] === "true") {
                      v.dataValue = "开启";
                      v.percentValue = "";
                    } else if (metadata[index] === "false") {
                      v.dataValue = "关闭";
                      v.percentValue = "";
                    } else {
                      if (v.dataValue == "0" && Number(metadata[index]) > 0) {
                        v.dataValue = metadata[index];
                        v.percentValue = "100.00";
                      } else if (
                        v.dataValue == "0" &&
                        Number(metadata[index]) < 0
                      ) {
                        v.dataValue = metadata[index];
                        v.percentValue = "-100.00";
                      } else {
                        v.dataValue = metadata[index];
                        v.percentValue = "0.00";
                      }
                    }
                  }
                }
              });
            }
          }
        }
      });
    },

    // 折线图初始化
    drawLine() {
      const that = this;
      // 基于准备好的dom，初始化echarts实例
      this.lineChart = this.$echarts.init(this.$refs.chart);
      this.option = echartOptionInit(30, 180);
      // 绘制图表
      this.lineChart.setOption(this.option);
      // 随浏览器变化响应大小
      window.onresize = function() {
        that.lineChart.resize();
      };
    },

    // 添加数据
    drawLineData() {
      this.option = echartOptionLine(this.xData, this.yData);
      // 绘制图表
      this.lineChart.setOption(this.option);
      // /this.lineChart.resize();
    },
    // 清理折线图原有数据
    clearLineData() {
      this.xData = [];
      this.yData = [];
      this.option = echartOptionLine(this.xData, this.yData);
      this.option.title = {
        text: "暂无数据",
        left: 7,
        textStyle: {
          color: "#CCCCCC",
          fontSize: 16
        }
      };
      // 绘制图表
      this.lineChart.setOption(this.option);
    }
  }
};
</script>

<style lang="scss" scoped>
.pointList {
  margin-top: 25px;
  width: 100%;
  height: 180px;
  .pointLayout {
    display: flex;
    flex-wrap: wrap;
    margin-left: 7%;
    height: 170px;
    overflow: hidden;
  }
}
.el-icon-arrow-left {
  color: #e4e4e4;
  float: left;
  font-size: 45px;
  margin-top: 50px;
  margin-left: 2%;
}
.invalid {
  color: #e4e4e4 !important;
}
.el-icon-arrow-left:hover {
  color: #707070;
  cursor: pointer;
}
.el-icon-arrow-right {
  color: #e4e4e4;
  float: right;
  font-size: 45px;
  margin-top: -78px;
  margin-right: 2%;
}
.el-icon-arrow-right:hover {
  color: #707070;
  cursor: pointer;
}
.cardItem {
  height: 100%;
  width: 13%;
}
.listCard {
  margin-left: 10px;
  margin-top: 10px;
  background: #f5f5f5;
  border-radius: 2px;
  .itemBox {
    display: flex;
    align-content: space-between;
    flex-wrap: wrap;
    padding: 14px;
    height: 170px;
  }
}
.listCard:hover {
  cursor: pointer;
  background-color: #f2fbff;
}
.parameter {
  width: 100%;
  height: 20%;
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #aeaeae;
}
.number {
  width: 100%;
  height: 20%;
  font-size: 30px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #333333;
}
.percentage {
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
}
.percentage_up {
  color: #6fa332;
}
.percentage_down {
  color: #f22735;
}
.percentage_com {
  color: #c0c4cc;
}
.bg_color {
  background-color: #2680d2;
}
.bg_color:hover {
  background-color: #2680d2;
}
.word_color {
  color: #fff;
}
.word_color:hover {
  color: #fff;
}

// 分页样式自定义
.smallPaging {
  /* float: right; */
  /* margin: 0px 8% 0 0; */
  width: 100%;
  text-align: center;
}
/deep/.smallPaging .el-pagination .btn-prev {
  display: none;
}
/deep/.smallPaging .el-pagination .btn-next {
  display: none;
}
/deep/.smallPaging .el-pager li.active {
  cursor: default;
  height: 8px;
  border-radius: 50%;
  background: #2680d2;
  min-width: 0px;
  width: 8px;
  color: #fff;
}
/deep/.smallPaging .el-pager li {
  min-width: 0px;
  width: 8px;
  height: 8px;
  background: #cccccc;
  border-radius: 50%;
  color: #ccc;
  margin-left: 8px;
  font-size: 0px;
}
/deep/.smallPaging .el-pager li:last-child {
  height: 8px;
  min-width: 0;
  font-size: 0px;
}
/deep/.smallPaging .el-pager li:hover {
  color: #2680d2;
  background-color: #2680d2;
}
/deep/.smallPaging .el-pager li.active {
  font-size: 0px;
}

//echarts
.data-charts {
  /* margin-top: 33px; */
}
.chart {
  height: calc(100vh - 150px - 40px - 215px);
}
</style>
